package com.heihei.utils;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.apache.commons.lang3.StringUtils;

/**
 * 拼音工具类
 *
 */
public class PinyinUtil {

    /**
     * 方法描述  将包含汉字的字符串转换为拼音
     *
     */
    public static String convertHanziToPinyin(String source) throws BadHanyuPinyinOutputFormatCombination {
        if (StringUtils.isEmpty(source)) {
            return source;
        }
        StringBuilder sb = new StringBuilder("");
        //1.创建一个格式化输出对象
        HanyuPinyinOutputFormat outputF = new HanyuPinyinOutputFormat();
        //2.设置好格式
        outputF.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        outputF.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        char[] chars = source.toCharArray();
        for (char ch : chars) {
            String[] strArr = PinyinHelper.toHanyuPinyinStringArray(ch, outputF);
            if (strArr == null) {
//                sb.append(ch);
            } else {
                sb.append(strArr[0]);
            }
        }
        return sb.toString();
    }

    public static void main(String[] args) throws BadHanyuPinyinOutputFormatCombination {
        String result=convertHanziToPinyin("other");
        System.out.println(result);
    }
}
